/*==============================================================================
 * AUTH: Matthew Baum, 9753095
 *       Domenico Romano, 5574331
 * 
 * DATE: January-29-2012
 * DESC: Main Java class to read Task data from an XML file, groups all tasks for each assignee together and prints it
 *       out to standard output and XML file.
 *==============================================================================*/

package Phase_1;

// Import Java File handling libraries
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

// Import Java XML Parsing Libraries
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.ParserConfigurationException;

import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

// Import W3C (WWW Consortium) XML DOM Libraries
import org.w3c.dom.*;


public class Main {

	// An array to hold some task objects:
	private static Task[] tasks;

	// MAIN:
	public static void main(String[] args) {

		// Factory design pattern to produce DocumentBuilders:
		DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();

		try
		{
			// Use factory to generate a new document builder:
			DocumentBuilder builder = docBuilderFactory.newDocumentBuilder();

			// Create a Document object by parsing the XML document:
			Document document = builder.parse (new File("tasks.xml"));

			// Get all task items:
			NodeList taskList = document.getElementsByTagName("task");

			// INIT the task object array:
			tasks = new Task[ taskList.getLength() ];
      
       if (taskList.getLength() == 0) {
				System.out.println("Empty task list given.");
				System.exit(0);
			}
      
			// Process task items:
			for(int i = 0; i != taskList.getLength(); ++i)
			{
				// Get a task item:
				Node task = taskList.item(i);

				// Create a Task object from the XML DOM node:
				tasks[i] = Task.getTaskFromXMLNode(task);
			}
		}
		catch (ParserConfigurationException PCe)
		{
			System.out.println("An exception occured in configuring the XML parser!");
			PCe.printStackTrace(System.out);
		}
		catch (IOException IOe)
		{
			System.out.println("An Input/Output Exception occured while parsing an xml document!");
			IOe.printStackTrace(System.out);
		}
		catch (Exception e)
		{
			System.out.println("AN UNRECOGNIZED ERROR HAS OCCURED!");
			e.printStackTrace(System.out);
		}


		// Obtain list of distinct employee names
		ArrayList<String> listOfNames = DataHelpers.listEmployees(tasks);

		// Obtain HashMap associating Tasks to names
		HashMap<String, ArrayList<Task> > taskAssignments = DataHelpers.getTaskAssignments(tasks);

		// Create array of People objects
		Person[] people = new Person[ listOfNames.size() ];

		// Populate array of People, by iterating over Map
		for(int i = 0; i != listOfNames.size(); ++i)
		{
			// Get employee name
			String name = listOfNames.get(i);

			// Set new Person Object
			people[i] = new Person(name, taskAssignments.get(name).toArray(new Task[1]) );
		}


		try {

			DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
			DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

			// root elements
			Document doc = docBuilder.newDocument();
			Element assign = doc.createElement("WorkersAndTasks");
			doc.appendChild(assign);




			for(int i = 0; i != people.length; ++i){

				String tempName = people[i].getAssgn();

				Element wrks = doc.createElement("Worker");
				assign.appendChild(wrks);

				wrks.setAttribute("Name",tempName);


				int arrayLength = people[i].getTasks().length;
				Task[] tempy = new Task[arrayLength];

				tempy = people[i].getTasks();


				System.out.println();
				System.out.println(people[i].getAssgn());	//test output to java console

				for(int f = 0; f != tempy.length; ++f){

					if(tempy[f] == null)
						break;

					System.out.println(tempy[f]);		//test output to java console

					// task id elements
					String id = Integer.toString(tempy[f].getID());	 //as doc.createTextNode() requires a string and not an int

					Element taskId = doc.createElement("TaskID");
					taskId.appendChild(doc.createTextNode(id));
					wrks.appendChild(taskId);

					/* TASK DESCRIPTION AND HOURS/TASK, IF LATER NEED FOR OUTPUT XML FILE, OR ELSE REMOVE
					// task description elements
					Element taskDesc = doc.createElement("TaskDescription");
					taskDesc.appendChild(doc.createTextNode(tempy[f].getTitle()));
					assign.appendChild(taskDesc);

					// hours elements
					String dur = Integer.toString(tempy[f].getDuration());	//as doc.createTextNode() requires a string and not an int

					Element hours = doc.createElement("Duration");
					hours.appendChild(doc.createTextNode(dur));
					assign.appendChild(hours);
					 */
				}


				//total hrs element
				String tTime = Integer.toString( people[i].getHours() );	//as doc.createTextNode() requires a string and not an int


				wrks.setAttribute("TotalHrs", tTime);




				System.out.println("Total Hours: " + people[i].getHours() ); //test output to java console"


			}







			// write the content into xml file
			TransformerFactory transformerFactory = TransformerFactory.newInstance();
			Transformer transformer = transformerFactory.newTransformer();

			DOMSource source = new DOMSource(doc);
			StreamResult result = new StreamResult(new File("output.xml"));

			transformer.transform(source, result);

			System.out.println("File saved!");	




		} 
		catch (ParserConfigurationException pce)
		{
			pce.printStackTrace(System.out);
		} 
		catch (TransformerException tfe)
		{
			tfe.printStackTrace(System.out);
		}
	}

}
